<?php

namespace App\Console\Commands;

use App\Http\Models\Mysql\ProductSubcontractTable;
use App\Http\Models\Mysql\SsyJyProductListTable;
use App\Http\Models\Mysql\SsyProcessingFactoryNameTable;
use App\Http\Models\Mysql\SsyProcessingListBatchTable;
use App\Http\Models\Mysql\SsyProcessingListTable;
use App\Http\Models\Mysql\StyleTable;
use App\Http\Services\Produce\ProcessingManageService;
use Illuminate\Console\Command;
use Illuminate\Support\Carbon;
use Illuminate\Support\Facades\Cache;

class pullProcessing extends Command
{
    /**
     * The name and signature of the console command.
     *
     * @var string
     */
    protected $signature = 'command:pullProcessing {--processing_code=}';

    /**
     * The console command description.
     * /30 * * * *
     * @var string
     */
    protected $description = '同步成品加工单';

    /**
     * Create a new command instance.
     *
     * @return void
     */
    public function __construct()
    {
        parent::__construct();
    }

    public function handle()
    {
        $autoKey = "auto_pullProcessing";
        Cache::put($autoKey, 1, Carbon::now()->addMinutes(15));
        $processingCode = $this->option('processing_code') ?: "";
        $numbers = !empty($processingCode) ? explode(",", $processingCode) : [];
        $subjects = array_column(config("scm.subject"), null, "brand_id");
        $productSubcontractList = (new ProductSubcontractTable())->where(function($query) use($numbers){
            if(!empty($numbers)){
                $query->whereIn('number', $numbers);
            }else{
                $query->where('is_process', 0);
            }
        })->get()->toArray();
        if(empty($productSubcontractList)){
            Cache::forget($autoKey);
            die("暂无数据更新");
        }
        foreach ($productSubcontractList as $productObj){
            $exist = (new SsyProcessingListTable())->where('processing_code', $productObj['number'])->exists();
            if($exist){
                echo "已存在, 无需处理：".trim($productObj['number'])."\n";
                (new ProductSubcontractTable())->updateDataWhere(['number' => $productObj['number']], ["is_process" => 1]);
                continue;
            }
            //获取工厂id supplier_id
            $factoryObj = (new SsyProcessingFactoryNameTable())->where('factory_name', $productObj['supplier'])->first(['supplier_id', 'factory_name']);
            $factoryObj = !empty($factoryObj) ? $factoryObj->toArray() : [];
            if(empty($factoryObj)){
                echo "加工厂不存在：".$productObj['number']."：".$productObj['supplier']."\n";
                continue;
            }
            $createTime = date('Y-m-d H:i:s');
            $detailObj = (new ProcessingManageService())->detail($productObj['id']);
            $styleObj = (new StyleTable())->where('number', $detailObj['item']['product_number'])->first(['brand_id']);
            $brandName = $subjects[$styleObj->brand_id]['brand_name'] ?? "";
            $brandCode = $subjects[$styleObj->brand_id]['brand_code_s'] ?? "";
            //获取批次信息
            //$batchObj = (new SsyProcessingListBatchTable())->where('batch_date', '>=', $detailObj['data']['delivery_date'])->where('status', 1)
            //    ->orderBy('batch_date', 'asc')->first();
            foreach ($detailObj['size_position'] as $item) {
                $countObj = $detailObj['detail_count'][$item['size']];
                if (empty($countObj['count'])) {
                    continue;
                }
                $skuCode = $detailObj['item']['product_number'] . $detailObj['item_colour']['colour_number'] . $countObj['item_size']['size_number'];
                $processingObj = (new SsyProcessingListTable())->where('processing_code', $detailObj['data']['number'])->where('sku_code', $skuCode)->first();
                if (empty($processingObj)) {
                    echo "正在处理：加工单：".$detailObj['data']['number']." sku: $skuCode\n";
                    $data = [
                        'type_name' => $detailObj['item']['product'],
                        'type_no' => $detailObj['item']['product_number'],
                        'color_code' => $detailObj['item_colour']['colour_number'],
                        'size_code' => $countObj['item_size']['size_number'],
                        'num' => $countObj['count'],
                        'sku_code' => $skuCode,
                        'processing_code' => $detailObj['data']['number'],
                        'factory_name' => $detailObj['data']['supplier'],
                        'supplier_id' => $factoryObj['supplier_id'],
                        'bunum' => $countObj['count'] + ceil($countObj['count'] * 0.05),//默认溢装比为50%,
                        'createtime' => $createTime,
                        'factory_contract_no' => $detailObj['data']['contract_number'],
                        'countnum' => $detailObj['data']['count'],
                        'countprice' => $detailObj['data']['price'],
                        'advance_charge' => $detailObj['data']['advance'],//预付款
                        'embroidery_price' => $detailObj['data']['f8_price'],
                        'contract_date' => $detailObj['data']['delivery_date'],
                        'production_date' => "",//生成回复交期
                        'merchandiser' => $detailObj['data']['handler'],
                        'order_processor' => $detailObj['data']['f18'],
                        'adduser' => $detailObj['data']['creator'],
                        'embroidery_factory' => $detailObj['data']['f8_short'],
                        'printing_factory' => $detailObj['data']['f9_short'],
                        'bronzing_factory' => $detailObj['data']['f10_short'],
                        'gold_printing_factory' => $detailObj['data']['f11_short'],
                        'unit_price' => $detailObj['data']['verify_price_price'],
                        'add_date' => $detailObj['item_detail']['customer_purchase_order_date'],
                        'tb_time' => $createTime,
                        'verify_price_number' => $detailObj['data']['verify_price_number'], //大货核价编码
                        'export_order_number' => $detailObj['item']['export_order_number'], //运营订单编码
                        "source_type"         => 2,//加工单接口获取
                        's_status' => $detailObj['data']['approval_state'] == 0 ? 0 : 1,//0未审核 1已审核
                        //"batch_no"            => $batchObj->batch_no ?? "",
                        //"batch_title"         => $batchObj->batch_title ?? "",
                        //"batch_date"          => $batchObj->batch_date ?? "",
                        "brand_name" => $brandName,
                        "brand_code" => $brandCode
                    ];
                    (new SsyProcessingListTable())->createData($data);
                }
                //同步合同交期
                $days = (strtotime($detailObj['data']['delivery_date']) - strtotime(date('Y-m-d'))) / (24*3600);
                (new SsyJyProductListTable())->updateDataWhere(['product_code' => $skuCode], [
                    'arrivaldate' => $detailObj['data']['delivery_date'],
                    'arrivaldate_title' => ((Int)$days)."天发货"
                ]);
            }
            (new ProductSubcontractTable())->updateData($productObj['id'], ["is_process" => 1]);
        }
        Cache::forget($autoKey);
    }
}
